package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.Car;
import com.example.demo.entity.Goods;
import com.example.demo.entity.Orders;
import com.example.demo.entity.User;
import com.example.demo.exception.ApplicationException;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.CarService;
import com.example.demo.mapper.CarMapper;
import com.example.demo.service.GoodsService;
import com.example.demo.vo.Result;
import com.example.demo.vo.ResultCode;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author 15085202591
* @description 针对表【car】的数据库操作Service实现
* @createDate 2024-05-31 16:05:25
*/
@Slf4j
@Service
public class CarServiceImpl extends ServiceImpl<CarMapper, Car> implements CarService{

    @Resource
    private CarMapper carMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private GoodsService goodsService;

    @Override
    public Integer addCarInfo(Long userId, Long goodId) {
        // 1. 校验参数
        if (userId == null || userId < 1 || goodId == null || goodId < 1) {
            log.warn("参数校验失败");
            throw new ApplicationException(Result.error(ResultCode.CLIENT_A0002));
        }

        // 2. 校验用户状态
        User existUser = userMapper.selectById(userId);
        if (existUser == null || existUser.getIsDeleted() == 1) {
            // 打印日志
            log.warn("用户不存在");
            // 抛出异常
            throw new ApplicationException(Result.error(ResultCode.CLIENT_A0201));
        }
        if (existUser.getStatus() == 0) {
            log.warn("用户状态异常");
            throw new ApplicationException(Result.error(ResultCode.CLIENT_A0006));
        }

        // 3. 根据 用户id 和 商品id 查出该记录是否存在
        QueryWrapper<Car> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("good_id", goodId);
        Car exist = carMapper.selectOne(wrapper);

        if (exist != null) {
            log.info("购物车已有商品信息");
            return 0;
        }

        // 4. 记录不存在, 插入一条数据
        // 根据商品id查出商品信息
        Goods goods = goodsService.getGoodsById(goodId);
        if (goods == null) {
            log.warn("商品已下架");
            throw new ApplicationException(Result.error(ResultCode.CLIENT_A0013));
        }
        // 组装数据
        Car car = new Car();
        car.setUserId(userId);
        car.setGoodId(goodId);
        car.setNumber(1L);
        // 设置价格
        if (goods.getDiscountedPrice() == 0) {
             // 设置保留两位小数的格式
            DecimalFormat df = new DecimalFormat("#.00");
            // 格式化数值并转换为double类型
            double formattedValue = Double.parseDouble(df.format( goods.getPrice() * 0.95));
            car.setGoodsPrice(formattedValue);
        }else {
            car.setGoodsPrice(goods.getDiscountedPrice());
        }
        car.setGoodsPicture(goods.getPicture());
        car.setGoodsName(goods.getGoodsName());
        car.setAddress(goods.getAddress());
        // 设置时间
        LocalDateTime dateTime = LocalDateTime.now();
        car.setCreateTime(dateTime);
        car.setUpdateTime(dateTime);
        //调用mapper
        int row = carMapper.insert(car);
        if (row != 1) {
            log.warn("新增失败");
            throw new ApplicationException(Result.error(ResultCode.CLIENT_A9999));
        }

        // 成功打印日志
        log.info("加入购物车成功");
        return 1;

    }

    @Override
    public void deleteById(Long id) {
        // 1. 校验参数
        if (id == null || id < 1) {
            log.warn("参数校验失败");
            throw new ApplicationException(Result.error(ResultCode.CLIENT_A0002));
        }

        // 2. 调用mapper
        int row = carMapper.deleteById(id);
        if (row != 1) {
            log.warn("删除购物车记录失败");
            throw new ApplicationException(Result.error(ResultCode.CLIENT_A9999));
        }

        log.info("购物车记录删除成功");

    }

    @Override
    public List<Car> getCarByUid(Long userId) {
        // 1. 校验参数
        if (userId < 0) {
            log.warn("参数校验失败");
            throw new ApplicationException(Result.error(ResultCode.CLIENT_A0002));
        }

        // 2. 调用mapper
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("user_id", userId);
        List<Car> carsList = carMapper.selectByMap(columnMap);

        // 3. 返回结果
        return carsList;
    }

    @Override
    public List<Car> getAllCarInfoByUid(Long userId) {
        // 1. 校验参数
        if (userId < 1) {
            log.warn("参数校验失败");
            throw new ApplicationException(Result.error(ResultCode.CLIENT_A0002));
        }

        // 2. 调用mapper
        QueryWrapper<Car> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).orderByDesc("cid");
        List<Car> cars = carMapper.selectList(wrapper);

        // 3. 成功返回
        log.info("查询成功");
        return cars;
    }
}




